/**
 * @description snabbdom 库的使用
 * @author xfj
 */

import {
    init,
    classModule,
    propsModule,
    styleModule,
    eventListenersModule,
    h,
} from "snabbdom";
import './index.css';

const patch = init([
    classModule, // makes it easy to toggle classes
    propsModule, // for setting properties on DOM elements
    styleModule, // handles styling on elements with support for animations
    eventListenersModule, // attaches event listeners
]);

// 创建顶部工具栏，包含新增按钮
const toolBar = h('div#toolbar', [
    h('button#add', {
        on: {
            click: handleAddList
        }
    }, 'Add'),
    h('button#sort', {
        on: {
            click: handleSortList
        }
    }, 'Sort(id)')
]);

// 点击 Add 时的事件
function handleAddList() {
    const length = data.length;
    data.push({id: length, content: `新加的第${length+1}条数据`});
    list = patch(list, createListNode());
}

function handleSortList() {
    let mock = [2, 3, 5, 10, 23, 43, 66, 67, 89, 99];
    data = [];
    for(let i = 0, len = mock.length; i < len; i++) {
        data.push({
            id: mock[i],
            content: `这是第${mock[i]}条数据`
        })
    }
    list = patch(list, createListNode());
}

// 组装列表上的数据
let mock = [2, 3, 5, 10, 43, 23, 66, 67, 89, 99];
let data = [];
for(let i = 0, len = mock.length; i < len; i++) {
    data.push({
        id: mock[i],
        content: `这是第${mock[i]}条数据`
    })
}
// 创建列表的 VNode
function createListNode() {
    const children = [];
    for(let i = 0, len = data.length; i < len; i++) {
        const item = data[i];
        const node = h('li.list-item', {
            key: item.id,
        }, [
            h('div', item.content),
            h('div.delBtn', {
                on: {
                    click: () => handleDelList(item.id)
                }
            }, '删除')
        ])
        children.push(node);
    }
    return h('ul#list', {}, children);
}

// 删除数据
function handleDelList(index) {
    data.splice(index, 1);
    list = patch(list, createListNode());
}

// 创建列表的 vnode
let list = createListNode();

// 集合 toolBar 和 list， 形成 vnode
const node = h('div#app', [
    toolBar,
    list
])

// 第一次渲染
const root = document.getElementById("app");
patch(root, node);
